import {
  PageContainer,
  ProForm,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
  ProTable,
} from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Space,
  Popconfirm,
  Image,
  Drawer,
  Tag,
  message,
  Checkbox,
  Tree,
  Divider,
} from "antd";
import { connect } from "umi";
import {
  namespace,
  calcColumns,
  flattenTree,
  flattenTreeLabel,
  MenutagList,
  disableKeysInTree,
} from "./configFile";
import { useEffect, useRef, useState } from "react";
import default_avater_female from "@/assets/imgs/default_avater_female.png";
import { PlusOutlined } from "@ant-design/icons";
import Https from "@/utils/Https";
import styles from "./style.less";
const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [open, setOpen] = useState(false);
  const [openAllocated, setOpenAllocated] = useState(false);
  const [roleId, setRoleId] = useState(false);
  const [status, setStatus] = useState(0);
  const [roleKey, setRoleKey] = useState("");
  const formRef = useRef();
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [menu, setMenu] = useState([]);
  const [allMenuId, setAllMenuId] = useState([]);
  const [menusLabel, setMenusLabel] = useState({});
  const [checked, setChecked] = useState(false);
  const [baseRoleList, setBaseRoleList] = useState([]);
  const [editStatus, setEditStatus] = useState("1");
  const [baseRoleId, setBaseRoleId] = useState("");
  const [hasBaseRole, setHasBaseRole] = useState(false);
  const [baseRoleMenus, setBaseRoleMenus] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const editInfo = (params) => {
    formRef?.current?.resetFields();
    setBaseRoleId("");
    setHasBaseRole(false);
    setChecked(false);
    dispatch({
      type: `${namespace}/queryRoleMenu`,
      params: params.roleId,
      callback: (res) => {
        formRef?.current?.setFieldsValue({
          ...res,
          menuIds: res.checkedKeys,
        });
        if (params.roleKey == "admin") {
          setCheckedKeys(res.checkedKeys);
        }
        setBaseRoleId(res.baseRoleId);
        setStatus(1);
        setOpen(true);
      },
    });
  };

  const openAllocatedModel = (record) => {
    setRoleId(record.roleId);
    setRoleKey(record.roleKey);
    actionRef2.current?.reload();
    setOpenAllocated(true);
  };
  //修改状态
  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
      },
    });
  };
  //删除角色
  const deleteItem = (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  //删除关联角色
  const deleteAuthUser = (params) => {
    dispatch({
      type: `${namespace}/deleteAuthUser`,
      params,
      callback: () => {
        actionRef2.current?.reload();
        actionRef.current?.reload();
      },
    });
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    width: 200,
    hideInSearch: true,
    render: (_, record) => {
      const { userCount, roleId } = record;
      return (
        <Space>
          {record.isSystem == "1" && (
            <Button
              type="link"
              onClick={() => {
                setEditStatus("2");
                editInfo(record);
                let newTree = disableKeysInTree(menu, []);
                setMenu([...newTree]);
              }}
            >
              查看
            </Button>
          )}
          {record.isSystem == "0" && (
            <Button
              type="link"
              onClick={() => {
                editInfo(record);
                setEditStatus("1");
              }}
            >
              编辑
            </Button>
          )}
          {record.isSystem == "0" && userCount == 0 ? (
            <Popconfirm
              title="确定要删除吗?"
              onConfirm={() => deleteItem(roleId)}
            >
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm>
          ) : (
            <Button disabled type="link" danger>
              删除
            </Button>
          )}
        </Space>
      );
    },
  };
  //获取基础角色数据
  const getBaseRoleList = async () => {
    let res = await Https.get("/system/role/baseRoleList", {}, true);
    if (res.code == 200) {
      let objList = [];
      if (res.data.length > 0) {
        res.data.map((item) =>
          objList.push({ ...item, label: item.roleName, value: item.roleId })
        );
      }
      setBaseRoleList(objList);
    } else {
      setBaseRoleList([]);
      message.error(res.msg);
    }
  };
  //获取菜单数据
  const getMenuList = async () => {
    let res = await Https.get(
      "/system/menu/loadTenantPackageMenuTreeselect",
      {},
      true
    );
    if (res.code == 200 && res.data) {
      setMenu(res.data.menus);
      let menus = flattenTree(res.data.menus);
      let menusLabel = flattenTreeLabel(res.data.menus);
      setMenusLabel(menusLabel);
      setAllMenuId(menus);
    } else {
      setMenu([]);
      setAllMenuId([]);
      setMenusLabel({});
      message.error(res.msg);
    }
  };
  const submitForm = async () => {
    const res = await formRef?.current?.validateFields();
    if (res) {
      let arr = [];
      res.menuIds.forEach((m) => {
        if (m.label) {
          arr.push(m.value);
        } else {
          arr.push(m);
        }
      });
      res.menuIds = [...new Set(arr)];
      dispatch({
        type: `${namespace}/submitItem`,
        params: { ...res, roleSort: 1 },
        callback: (res) => {
          setOpen(false);
          actionRef.current?.reload();
        },
      });
    }
  };
  useEffect(() => {
    getMenuList();
    getBaseRoleList();
  }, []);
  useEffect(() => {
    if (baseRoleList.length > 0 && baseRoleId && menu.length > 0) {
      let baseMenus = baseRoleList.filter(function (o) {
        return o.roleId == baseRoleId;
      });
      let menuIdList = [];
      if (baseMenus.length > 0) {
        menuIdList = baseMenus[0].menuIdList;
      }
      setBaseRoleMenus(menuIdList);
      if (editStatus == "1") {
        let newTree = disableKeysInTree(menu, menuIdList);
        setMenu([...newTree]);
      }
      if (hasBaseRole) {
        formRef.current.setFieldsValue({
          menuIds: menuIdList,
        });
      }
      if (editStatus == "2") {
        setCheckedKeys(menuIdList);
      }
    }
  }, [baseRoleId]);
  return (
    <PageContainer>
      <ProTable
        // scroll={{ x: 1500 }}
        actionRef={actionRef}
        rowKey="roleId"
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              formRef?.current?.resetFields();
              setStatus(0);
              setBaseRoleId("");
              setOpen(true);
              setEditStatus("1");
              setHasBaseRole(false);
              setChecked(false);
              let newTree = disableKeysInTree(menu, []);
              setMenu([...newTree]);
            }}
          >
            新建角色
          </Button>,
        ]}
        pagination={{
          showSizeChanger: true,
        }}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        columns={calcColumns({ operate, openAllocatedModel, toggleState })}
      />
      <Drawer
        open={open}
        title={
          editStatus != "1" ? "查看角色" : status ? "修改角色" : "新增角色"
        }
        forceRender
        width="50%"
        onClose={() => setOpen(false)}
        footer={
          editStatus == "1" && (
            <Space
              style={{
                width: "100%",
                display: "flex",
                justifyContent: "flex-end",
              }}
            >
              <Button
                onClick={() => {
                  formRef?.current?.resetFields();
                  setOpen(false);
                }}
                size="large"
              >
                取消
              </Button>
              <Button
                onClick={submitForm}
                loading={submitLoading}
                size="large"
                type="primary"
              >
                确定
              </Button>
            </Space>
          )
        }
      >
        <ProForm
          formRef={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          submitter={false}
          layout="horizontal"
        >
          <Form.Item name="roleId" hidden>
            <Input />
          </Form.Item>
          {editStatus == "1" && (
            <ProFormRadio.Group
              label="基准角色"
              name="baseRoleId"
              options={baseRoleList}
              fieldProps={{
                onChange: (e) => {
                  let { value } = e.target;
                  setBaseRoleId(value);
                  setHasBaseRole(true);
                },
              }}
              rules={[{ required: true, message: "请选择基准角色" }]}
            />
          )}
          <ProFormText
            label="角色名称"
            name="roleName"
            readonly={editStatus != "1"}
            fieldProps={{
              maxLength: 20,
              showCount: true,
            }}
            rules={[{ required: true, message: "角色名称不能为空" }]}
            allowClear
            placeholder="请输入角色名称"
          />

          <ProFormTextArea
            label="角色描述"
            name="remark"
            readonly={editStatus != "1"}
            fieldProps={{
              maxLength: 200,
              showCount: true,
            }}
            allowClear
            placeholder="请输入备注"
            style={{ height: "200px" }}
          />
          {editStatus == "1" ? (
            <Form.Item label="菜单权限" required={true}>
              <Form.Item noStyle>
                <Checkbox
                  checked={checked}
                  style={{ verticalAlign: "middle", margin: "5px 0 10px" }}
                  onChange={(e) => {
                    let { checked } = e.target;
                    if (checked) {
                      formRef?.current?.setFieldsValue({ menuIds: allMenuId });
                    } else {
                      formRef?.current?.setFieldsValue({
                        menuIds: baseRoleMenus,
                      });
                    }
                    formRef?.current?.validateFields(["menuIds"]);
                    setChecked(checked);
                  }}
                >
                  全选
                </Checkbox>
              </Form.Item>
              <ProFormTreeSelect
                noStyle
                label=""
                name="menuIds"
                debounceTime={1000}
                fieldProps={{
                  treeCheckable: true,
                  treeCheckStrictly: true,
                  showCheckedStrategy: "SHOW_ALL",
                  treeTitleRender: (node) => {
                    return (
                      node && (
                        <span>
                          {node.menuType && (
                            <Tag color={MenutagList[node.menuType].color}>
                              {node.tenantType == "0" ? "品牌" : "场馆"}
                              <Divider
                                style={{
                                  borderColor: MenutagList[node.menuType].color,
                                }}
                                type="vertical"
                              />
                              {MenutagList[node.menuType].text}
                            </Tag>
                          )}
                          {node.label}
                        </span>
                      )
                    );
                  },
                  tagRender: (props) => {
                    const { value, closable, onClose } = props;
                    const label = menusLabel[value] || value;
                    return (
                      <span className={styles.customTag}>
                        {label}
                        {closable ? (
                          <span
                            onClick={onClose}
                            className={styles.customTagIcon}
                          >
                            &times;
                          </span>
                        ) : null}
                      </span>
                    );
                  },
                  fieldNames: {
                    value: "id",
                  },
                  treeData: menu,
                  allowClear: false,
                }}
                rules={[{ required: true, message: "功能权限不能为空" }]}
              />
            </Form.Item>
          ) : (
            <Form.Item label="菜单权限" name="menuIds" required={true}>
              <div style={{ border: "1px solid #e9e8e8", padding: "15px" }}>
                <Tree
                  checkable
                  checkStrictly
                  defaultExpandAll
                  checkedKeys={checkedKeys}
                  titleRender={(node) => {
                    return (
                      node && (
                        <span>
                          {node.menuType && (
                            <Tag color={MenutagList[node.menuType].color}>
                              {node.tenantType == "0" ? "品牌" : "场馆"}
                              <Divider
                                style={{
                                  borderColor: MenutagList[node.menuType].color,
                                }}
                                type="vertical"
                              />
                              {MenutagList[node.menuType].text}
                            </Tag>
                          )}
                          {node.label}
                        </span>
                      )
                    );
                  }}
                  fieldNames={{
                    title: "label",
                    key: "id",
                  }}
                  treeData={menu}
                />
              </div>
            </Form.Item>
          )}
        </ProForm>
      </Drawer>
      <Modal
        open={openAllocated}
        title="查看关联名单"
        forceRender
        width="60%"
        onCancel={() => setOpenAllocated(false)}
        footer={
          <Space>
            <Button
              onClick={() => {
                setOpenAllocated(false);
              }}
            >
              关闭
            </Button>
          </Space>
        }
      >
        <ProTable
          search={false}
          options={false}
          rowKey="userId"
          scroll={{ y: 500 }}
          actionRef={actionRef2}
          request={async (params) => {
            return await dispatch({
              type: `${namespace}/queryAuthUser`,
              params: {
                ...params,
                roleId,
              },
            });
          }}
          pagination={{
            showSizeChanger: true,
          }}
          columns={[
            {
              title: "头像",
              dataIndex: "avatar",
              render: (_, record) => {
                return (
                  <Image
                    src={record.avatar || default_avater_female}
                    width={60}
                  />
                );
              },
            },
            {
              title: "昵称",
              dataIndex: "nickName",
            },
            {
              title: "账号",
              dataIndex: "userName",
            },
            {
              title: "最后登录时间",
              dataIndex: "loginDate",
            },
            {
              title: "操作",
              fixed: "right",
              dataIndex: "options",
              render: (_, record) => {
                return roleKey == "admin" && record.mainFlag == 1 ? (
                  ""
                ) : (
                  <Popconfirm
                    title="确定要删除吗?"
                    onConfirm={() =>
                      deleteAuthUser({
                        userId: record.userId,
                        roleId,
                      })
                    }
                  >
                    <a style={{ color: "red" }}>删除</a>
                  </Popconfirm>
                );
              },
            },
          ]}
        />
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
